<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/7/7
 * Time: 3:42 下午
 * description: Token.php
 */

namespace app\api\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Laminas\Stdlib\Exception\DomainException;

class Token
{
    /**
     * 生成token
     */
    public function encode($user_id){
        $key = 'example_key';
        $payload = [
            'iss' => 'http://www.month.com',
            'aud' => 'http://www.month.com',
            'iat' => time(),
            'nbf' => time(),
            'user_id' => $user_id
        ];

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        return JWT::encode($payload, $key, 'HS256');
    }

    /**
     * 验证token
     */
    public function decode(){

        $key = 'example_key';
        $jwt = isset($_SERVER['HTTP_AUTHORIZATION']) ?  str_replace(["Bearer ","Bearer"],"",$_SERVER['HTTP_AUTHORIZATION']) : request()->all('token');

        if (empty($jwt)) {
            return  false;
        }

        try {
            $decoded = JWT::decode($jwt, new Key($key, 'HS256'));

            /*
             NOTE: This will now be an object instead of an associative array. To get
             an associative array, you will need to cast it as such:
            */

            $decoded_array = (array) $decoded;
            return isset($decoded_array['user_id']) ?$decoded_array['user_id']  : false;
        }catch (DomainException $domainException) {
            return  false;
        }

    }

}